package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exception.LyException;
import com.leyou.item.dto.SkuDTO;
import com.leyou.item.dto.SpuDTO;
import com.leyou.item.dto.SpuDetailDTO;
import com.leyou.item.entity.Sku;
import com.leyou.item.entity.Spu;
import com.leyou.item.entity.SpuDetail;
import com.leyou.item.mapper.SkuMapper;
import com.leyou.item.service.SkuService;
import com.leyou.item.service.SpuDetailService;
import com.leyou.item.service.SpuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class SkuServiceImpl extends ServiceImpl<SkuMapper, Sku> implements SkuService {
    @Autowired
    private SpuDetailService spuDetailService;

    @Autowired
    private SkuService skuService;

    @Autowired
    private SpuService spuService;

    @Override
    public List<SkuDTO> listSkuByIds(List<Long> ids) {

        return SkuDTO.convertEntityList(this.spuDetailService.listByIds(ids));
    }

    @Override
    public List<SkuDTO> skuBySpuId(Long spuID) {

       return  SkuDTO.convertEntityList(this.skuService.query().eq("spu_id",spuID).list());
    }

    @Override
    public void addGoods(SpuDTO spuDTO) {
        // 1.新增Spu
        Spu spu = spuDTO.toEntity(Spu.class);
        spu.setSaleable(false);

        boolean success = spuService.save(spu);
        if (!success) {
            throw new LyException(500, "新增商品失败");
        }
        // 2.新增SpuDetail
        SpuDetail spuDetail = spuDTO.getSpuDetail().toEntity(SpuDetail.class);
        spuDetail.setSpuId(spu.getId());
        success = spuDetailService.save(spuDetail);
        if (!success) {
            throw new LyException(500, "新增商品详情失败");
        }
        // 3.新增Sku
        List<Sku> list = spuDTO.getSkus().stream().map(skuDTO -> {
            Sku sku = skuDTO.toEntity(Sku.class);
            sku.setSaleable(false);
            sku.setSpuId(spu.getId());
            return sku;
        }).collect(Collectors.toList());
        // 批量新增
        skuService.saveBatch(list);

    }
    @Transactional
    @Override
    public void updatagoods(SpuDTO spuDTO) {
        // 1.修改spu
        // 1.1.判断是否存在spu的id，有说明需要修改，没有说明不需要
        Long spuId = spuDTO.getId();
        if(spuId != null){
            // 1.2.spu需要修改，更新spu, 转换dto
            Spu spu = spuDTO.toEntity(Spu.class);
            // 1.3.更新
            boolean success =this.spuService.updateById(spu);
            if(!success){
                // 更新失败，抛出异常
                throw new LyException(500, "更新商品失败！");
            }
        }
        // 2.修改spuDetail
        SpuDetailDTO detailDTO = spuDTO.getSpuDetail();
        // 2.1.判断是否为null
        if (detailDTO != null && detailDTO.getSpuId() != null) {
            // 2.2.spuDetail存在，需要修改，转换DTO
            SpuDetail detail = detailDTO.toEntity(SpuDetail.class);
            boolean success = spuDetailService.updateById(detail);
            if(!success){
                // 更新失败，抛出异常
                throw new LyException(500, "更新商品失败！");
            }
        }
        // 3.修改sku
        List<SkuDTO> dtoList = spuDTO.getSkus();
        // 3.1.判断是否包含sku
        if(CollectionUtils.isEmpty(dtoList)){
            return;
        }
        // 3.2.转换DTO，并将sku根据saleable是否为null来分组。null，是新增或修改，不是null是删除
        Map<Boolean, List<Sku>> map = dtoList.stream()
                .map(skuDTO -> skuDTO.toEntity(Sku.class))
                .collect(Collectors.groupingBy(sku -> sku.getSaleable() == null));

        // 3.3.获取要新增或修改的sku
        List<Sku> insertOrUpdateList = map.get(true);
        // 如果不为空，则修改或新增
        if(!CollectionUtils.isEmpty(insertOrUpdateList)) {
            skuService.saveOrUpdateBatch(insertOrUpdateList);
        }

        // 3.4.获取要删除的sku
        List<Sku> deleteSkuList = map.get(false);
        if(!CollectionUtils.isEmpty(deleteSkuList)){
            // 存在要删除的sku
            List<Long> idList = deleteSkuList.stream().map(Sku::getId).collect(Collectors.toList());
            // 删除
            skuService.removeByIds(idList);
        }
    }


}